// 作者:wisher
// 时间:2023/6/24
// 说明:视频接口及爬虫采集代码

const db = uniCloud.database();
// const url = `https://www.feisuzyapi.com/api.php/provide/vod/`
const url = `https://jszyapi.com/api.php/provide/vod/at/json`
let reptileTimer = null

function copyPage(page) {
	return new Promise(async (okay, not) => {
		let res = {}
		try {
			res = await uniCloud.httpclient.request(
				`${url}?ac=detail&pg=${page+1}&h=48`, {
					method: 'get',
					headers: {
						"User-Agent": `Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36 Edg/114.0.1823.43`
					},
					dataType: 'json', // 指定返回值为json格式，自动进行parse
				})
			okay(res)
		} catch (e) {
			//TODO handle the exception
			okay(await copyPage(page))
		}
	})
}
const collection = db.collection('configs');
const videoclt = db.collection('videos');

function ruku(data) {
	return new Promise(async (okay, not) => {
		try {
			for (let v of data.list) {
				v.vod_play_from = v.vod_play_from.split("$$$")
				v.vod_play_url = v.vod_play_url.split("$$$")
				for (let i in v.vod_play_url) {
					v.vod_play_url[i] = v.vod_play_url[i].split("#")
					for (let i2 in v.vod_play_url[i]) {
						let v2 = v.vod_play_url[i][i2]
						v2 = v2.split("$")
						v.vod_play_url[i][i2] = {
							name: v2[0],
							url: v2[1]
						}
					}
				}
				v.vod_play_url = v.vod_play_url[1]
				v.vod_pubdate = (new Date(v.vod_pubdate).getTime()) || 946627200000

				let dbd = (await videoclt.where({
					vod_id: v.vod_id
				}).get()).data
				let has = dbd.length != 0;
				dbd = dbd[0]
				if (!has) {
					await videoclt.add(v)
				} else {
					await videoclt.doc(dbd._id).set(v)
				}
			}

			okay(`${data.page}拷贝完毕`)
		} catch (e) {
			setTimeout(async () => {
				okay(await ruku(data))
			}, 1000)
			//TODO handle the exception
		}
	})

}
reptile2 = async () => {
	if (reptileTimer == null) return;
	let page = (await collection.where({
		name: "reptilePage"
	}).get()).data[0].value
	let cpage = page
	let copyPromis = []
	let count = 25
	while (cpage - page < count) {
		copyPromis.push(copyPage(cpage))
		cpage = cpage + 1
	}
	let data_ = await Promise.all(copyPromis)
	let rukus = []
	for (let res of data_) {
		let data = res.data
		rukus.push(ruku(data))
	}
	for (let v of (await Promise.all(rukus))) {
		console.log(v)
	}
	if (data_[data_.length - 1].data.page >= data_[data_.length - 1].data.pagecount) {
		reptileTimer = null
		await reptileStateSet(2)
		
		let d = (await db.collection('videos').aggregate()
			.group({
				_id: '$vod_id',
				'count': {
					'$sum': 1
				}
			})
			.match({
				'count': {
					'$gt': 1
				}
			})
			.end()).data
		for (let v of d) {
			let s = (await db.collection('videos')
				.where({
					vod_id: v._id
				})
				.get()
			).data
			await db.collection('videos').doc(s[0]._id).remove()
		}
		console.log(d.length)
		console.log(`全部拷贝完毕`)
	}
	await collection.where({
		name: "reptilePage"
	}).update({
		value: page + count
	})
	if (reptileTimer == null) return;
	reptileTimer = setTimeout(reptile2, 1000)
}


reptile = async () => {
	console.log({
		reptileTimer
	})
	if (reptileTimer == null) return;
	const collection = db.collection('configs');
	const videoclt = db.collection('videos');
	let page = (await collection.where({
		name: "reptilePage"
	}).get()).data[0].value
	console.log(`${page}开始拷贝`)
	let res = {}
	try {
		res = await uniCloud.httpclient.request(
			`${url}?ac=detail&pg=${page+1}`, {
				// `${url}?ac=detail&h=48&pg=${page+1}`, {
				method: 'get',
				headers: {
					"User-Agent": `Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36 Edg/114.0.1823.43`
				},
				dataType: 'json', // 指定返回值为json格式，自动进行parse
			})
	} catch (e) {
		//TODO handle the exception
		console.log(`${page}拷贝失败，5秒后重试`)
		reptileTimer = setTimeout(reptile, 5000)
		return
	}
	let data = res.data
	let list = []
	for (let v of data.list) {
		v.vod_play_from = v.vod_play_from.split("$$$")
		v.vod_play_url = v.vod_play_url.split("$$$")
		for (let i in v.vod_play_url) {
			v.vod_play_url[i] = v.vod_play_url[i].split("#")
			for (let i2 in v.vod_play_url[i]) {
				let v2 = v.vod_play_url[i][i2]
				v2 = v2.split("$")
				v.vod_play_url[i][i2] = {
					name: v2[0],
					url: v2[1]
				}
			}
		}
		v.vod_play_url = v.vod_play_url[1]

		let dbd = (await videoclt.where({
			vod_id: v.vod_id
		}).get()).data
		let has = dbd.length != 0;
		dbd = dbd[0]
		if (!has) {
			await videoclt.add(v)
		} else {
			await videoclt.doc(dbd._id).set(v)
		}
	}
	if (data.page >= data.pagecount) {
		reptileTimer = null
		await reptileStateSet(2)
	}
	console.log(`${page}拷贝完毕`, data.list)

	await collection.where({
		name: "reptilePage"
	}).update({
		value: page + 1
	})
	if (reptileTimer == null) return;
	reptileTimer = setTimeout(reptile, 1000)
}
reptileState = async () => {
	const collection = db.collection('configs');
	let res = (await collection.where({
		name: "reptileState"
	}).get()).data[0].value
	if (reptileTimer == null && res != 0) {
		res = 0
		await reptileStateSet(res)
	}
	if (reptileTimer != null && res == 0) {
		res = 1
		await reptileStateSet(res)
	}
	return res
}

reptileStateSet = async (state) => {
	const collection = db.collection('configs');
	await collection.where({
		name: "reptileState"
	}).update({
		value: state
	})
	if (state == 0 && reptileTimer != null) {
		reptileTimer = null
		clearTimeout(reptileTimer)
	}
}

module.exports = {
	async getSwiper(parms) {
		const collection = db.collection('swiper');
		let type_id = parseInt(parms.type_id) || 0
		let data = (await collection.where({
			type_id
		}).orderBy('vod_index', 'asc').get()).data
		return {
			mpserverlessComposedResponse: true,
			statusCode: 200,
			body: JSON.stringify(data)
		}
	},
	async reptileStart() {
		if (await reptileState() == 0) {
			console.log("开始")
			reptileTimer = setTimeout(() => {
				// reptile()
				reptile2()
			}, 1000)
		}
		return {
			code: 200
		}
	},
	async getClass() {
		const res = await uniCloud.httpclient.request(
			`${url}?ac=list&t=1&pg=5`, {
				method: 'get',
				headers: {
					"User-Agent": `Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36 Edg/114.0.1823.43`
				},
				dataType: 'json', // 指定返回值为json格式，自动进行parse
			})
		return res.data.class
	},
	async getList(t, p, n) {
		const res = await uniCloud.httpclient.request(
			`${url}?ac=detail${t?('&t='+t):""}${p?('&pg='+p):""}${n?('&wd='+n):""}`, {
				method: 'get',
				headers: {
					"User-Agent": `Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36 Edg/114.0.1823.43`
				},
				dataType: 'json', // 指定返回值为json格式，自动进行parse
			})
		return res.data.list
	},
	async getVideo(data) {
		let {
			id
		} = data
		const res = await uniCloud.httpclient.request(
			`${url}?ac=detail${id?('&ids='+id):""}`, {
				method: 'get',
				headers: {
					"User-Agent": `Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36 Edg/114.0.1823.43`
				},
				dataType: 'json', // 指定返回值为json格式，自动进行parse
			})
		return res.data.list
		// data = data
		// const videoclt = db.collection('videos');
		// let dbd = (await videoclt.where({
		// 	vod_id: data.id,
		// 	type_id: data.tid,
		// 	vod_name: new RegExp(data.name, 'ig'),
		// 	vod_actor: new RegExp(data.actor, 'ig'),
		// 	vod_area: new RegExp(data.area, 'ig'),
		// 	vod_year: new RegExp(data.year, 'ig'),
		// 	type_name: new RegExp(data.type, 'ig'),
		// }).limit(20).skip(data.page * 20).get()).data
		// if (dbd.length == 0 && data.name) {
		// 	const res = await uniCloud.httpclient.request(
		// 		`${url}?ac=detail&wd=${data.name}`, {
		// 			method: 'get',
		// 			headers: {
		// 				"User-Agent": `Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Mobile Safari/537.36 Edg/114.0.1823.43`
		// 			},
		// 			dataType: 'json', // 指定返回值为json格式，自动进行parse
		// 		})
		// 	dbd = res.data.list
		// }
		// return dbd
	},
	async postComment(vid, _id, com) {
		const collection = db.collection('comment');
		collection.add({
			vod_id: parseInt(vid),
			user_id: _id,
			com: com,
			date: new Date().getTime()
		})


		return {
			code: 200
		}
	},
	async getComment(vid) {
		const dbJQL = uniCloud.databaseForJQL({
			clientInfo: this.getClientInfo()
		})
		let data = (await dbJQL.collection('comment,users').where({
			'vod_id': parseInt(vid)
		}).field('user_id{username,avatarUrl},date,com,vod_id').orderBy('date desc').get())

		return data.data;
	}
}